package work.comeback.omo.controller.servlet.auth;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import work.comeback.omo.model.http.RequestParams;
import work.comeback.omo.model.user.UserBean;
import work.comeback.omo.service.UserService;
import work.comeback.omo.service.imp.UserServiceImpl;
import work.comeback.omo.util.common.AuthUtils;

import java.io.IOException;

public class ActionEventHandler {
    private static final Logger logger = LoggerFactory.getLogger(ActionEventHandler.class);
    private final UserService userService = new UserServiceImpl();
    private String cxtPath;
    private HttpSession session;

    private String addPath(String path) {
        return cxtPath.concat(path);
    }

    private String authenticate(RequestParams reqUser) {
        // captcha check
        if (AuthUtils.isCaptchaError(this.session)) {
            return "验证码错误";
        }

        // find db User
        UserBean dbUser = this.userService.findUserByUsername(reqUser.getUsername());

        if (dbUser == null) {
            return "用户不存在";
        }

        // encryptPassword
        String encString = AuthUtils.encryptPassword(reqUser.getPassword());

        // check pwd
        if (!dbUser.isSamePwd(encString)) {
            return "密码错误";
        }

        // set session
        AuthUtils.setUserSession(this.session, dbUser);

        logger.info("登录成功: {}", dbUser.getUsername());
        return "success";
    }

    private void handleLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        RequestParams requestParams = (RequestParams) request.getAttribute("requestParams");

        // 校验数据
        String msg = this.authenticate(requestParams);
        this.sendResp(request, response, msg);
    }

    private void handleLogout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // invalidate
        session.invalidate();

        // 重定向到首页
        resp.sendRedirect(this.addPath("/"));
        logger.info("Logout successful");
    }

    private void handleRegister(HttpServletRequest request, HttpServletResponse response) throws IOException {
        RequestParams requestParams = (RequestParams) request.getAttribute("requestParams");
        String username = requestParams.getUsername();
        String password = requestParams.getPassword();
        String encPwd = AuthUtils.encryptPassword(password);

        if (this.userService.hasRecord(username, encPwd)) {
            // 用户已存在
            this.sendResp(request, response, "用户已存在");
        } else {
            // 创建用户
            userService.createUser(
                    new UserBean(username, encPwd, "user")
            );
            String msg = this.authenticate(requestParams);
            this.sendResp(request, response, msg);
        }
    }

    private void sendResp(HttpServletRequest request, HttpServletResponse response, String msg) throws IOException {
        if (msg.equals("success")) {
            // 登录成功跳转主页
            response.sendRedirect(this.addPath("/"));
        } else {
            // 登录失败返回信息
            session.setAttribute("errMsg", msg);
            String backToCome = request.getHeader("referer");
            response.sendRedirect(backToCome);
        }
    }

    public void handleEvent(String action, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.session = req.getSession(true);
        this.cxtPath = req.getContextPath();

        // handle action
        switch (action) {
            case "login":
                this.handleLogin(req, resp);
                break;
            case "logout":
                this.handleLogout(req, resp);
                break;
            case "register":
                this.handleRegister(req, resp);
            default:
                break;
        }
    }
}
